package com.appcenter.task.service;


import com.appcenter.jz.config.ErrorJsonResult;
import com.appcenter.jz.config.JsonResult;
import com.appcenter.jz.page.PagedResult;
import com.appcenter.jz.unit.ObjectUnit;
import com.appcenter.task.config.RemoteProperties;
import com.appcenter.task.dto.Apps;
import com.appcenter.task.input.LoadUnTaskListPageInput;
import com.appcenter.task.input.SearchUnTaskListInput;
import com.appcenter.task.input.externalapi.ConversionTaskInput;
import com.appcenter.task.input.externalapi.SendTaskInput;
import com.appcenter.task.mapper.AlreadyTasksMapper;
import com.appcenter.task.mapper.UnTaskHistorysMapper;
import com.appcenter.task.mapper.UnTasksMapper;
import com.appcenter.task.model.AlreadyTasks;
import com.appcenter.task.model.UnTaskHistorys;
import com.appcenter.task.model.UnTasks;
import com.appcenter.task.output.LoadUnTaskListPageOutput;
import com.appcenter.task.output.SearchUnTaskListOutput;
import com.appcenter.task.output.externalapi.ConversionTaskOutput;
import com.appcenter.task.output.externalapi.SendTaskOutput;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import static com.appcenter.jz.unit.ObjectUnit.JsonUnit;
import static org.apache.http.util.TextUtils.isBlank;

@EnableConfigurationProperties(RemoteProperties.class)
@Service
public class UnTaskService {
    @Autowired
    UnTasksMapper unTasksMapper;
    @Autowired
    RemoteProperties remoteProperties;
    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    private HttpAPIService httpAPIService;
    @Autowired
    private AlreadyTasksMapper alreadyTasksMapper;
    @Autowired
    private UnTaskHistorysMapper unTaskHistorysMapper;
    /**
     *  创建人:Coke
     *  备注: 待办任务加载服务
     *  时间: 2019/4/26 14:48 
     *  参数: 
     */
    public LoadUnTaskListPageOutput LoadUnTaskListPage(LoadUnTaskListPageInput input) throws IOException {
        LoadUnTaskListPageOutput output = new LoadUnTaskListPageOutput();
        String GetAppsUrl = remoteProperties.getAppCenterServiceUrl() + "/app/getapps";
        String responseJson = httpAPIService.JsonSMS(GetAppsUrl, "{}");
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        JsonResult jsonResult = objectMapper.readValue(responseJson, JsonResult.class);
        List<Apps> apps = new ArrayList<Apps>();
        Object OneItems = JsonUnit(jsonResult.getResult(), "items");
        ArrayList<Object> TwoItems = (ArrayList<Object>) JsonUnit(OneItems, "items");
        if (TwoItems != null && TwoItems.size() > 0) {
            for (int i = 0; i < TwoItems.size(); i++) {
                Apps app = new Apps();
                app.setId(JsonUnit(TwoItems.get(i), "id").toString());
                app.setAppCode(JsonUnit(TwoItems.get(i), "appCode").toString());
                app.setAppName(JsonUnit(TwoItems.get(i), "appName").toString());
                apps.add(app);
            }
        }
        output.setApps(apps);
        output.setItems(SearchUnTaskList(input).getItems());
        return output;
    }
    /**
     *  创建人:Coke
     *  备注: 待办任务查询服务
     *  时间: 2019/4/26 14:48 
     *  参数: 
     */
    public SearchUnTaskListOutput SearchUnTaskList(SearchUnTaskListInput input){
        SearchUnTaskListOutput output = new SearchUnTaskListOutput();
        Example example = new Example(UnTasks.class);
        Example.Criteria criteriaKeyword = example.createCriteria();
        if(!isBlank(input.getKeyword())){
            criteriaKeyword.orLike("title", "%"+input.getKeyword()+"%");
            criteriaKeyword.orLike("content", "%"+input.getKeyword()+"%");
            criteriaKeyword.orLike("businessType", "%"+input.getKeyword()+"%");
            criteriaKeyword.orLike("receiveUserId", "%"+input.getKeyword()+"%");
            criteriaKeyword.orLike("receiveUserCode", "%"+input.getKeyword()+"%");
            criteriaKeyword.orLike("receiveUserName", "%"+input.getKeyword()+"%");
        }
        example.and(criteriaKeyword);

        Example.Criteria criteriaMain = example.createCriteria();
        if(!isBlank(input.getAppCode())){
            criteriaMain.andEqualTo("receiveAppCode", input.getAppCode());
        }
        if(!isBlank(input.getUserCode())){
            criteriaMain.andEqualTo("receiveUserId", input.getUserCode());
        }
        example.and(criteriaMain);
        PageHelper.startPage(input.getPage().getPageNo(), input.getPage().getPageSize(), "createTime desc");
        List<UnTasks> tasks = unTasksMapper.selectByExample(example);
        PageInfo<UnTasks> page = new PageInfo<>(tasks);
        output.setItems(new PagedResult<UnTasks>(page.getList(), (int) page.getTotal()));
        return output;
    }
    /**
     *  创建人:Coke
     *  备注: 发送待办
     *  时间: 2019/4/26 14:48 
     *  参数: 
     */
//    @Transactional
    public SendTaskOutput SendTask(SendTaskInput input) throws Exception {
        SendTaskOutput output = new SendTaskOutput();
        if(!isBlank(input.getBusinessId())){
            Example example = new Example(UnTasks.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("businessId", input.getBusinessId());
            List<UnTasks> unTasks=unTasksMapper.selectByExample(example);
            if(unTasks!=null && unTasks.size()>0){
                for (int i = 0; i <unTasks.size() ; i++) {
                    unTasksMapper.deleteByPrimaryKey(unTasks.get(i));
                }
            }
        }
        List<UnTasks> list = new ArrayList<UnTasks>();
        if(input.getReceiveUser()!=null && input.getReceiveUser().size()>0){
            for (int i = 0; i < input.getReceiveUser().size(); i++) {
                String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
                UnTasks curUnTasks = new UnTasks();
                ObjectUnit.Copy(input, curUnTasks);
                curUnTasks.setId(uuid);
                curUnTasks.setCreateTime(new Date());
                curUnTasks.setReceiveUserId(input.getReceiveUser().get(i).getReceiveUserId());
                curUnTasks.setReceiveUserCode(input.getReceiveUser().get(i).getReceiveUserCode());
                curUnTasks.setReceiveUserName(input.getReceiveUser().get(i).getReceiveUserName());
                unTasksMapper.insertSelective(curUnTasks);
                list.add(curUnTasks);
            }
        }
        output.setTasks(list);
        return output;
    }
    /**
     *  创建人:Coke
     *  备注: 待办转已办
     *  时间: 2019/4/26 14:53
     *  参数: 
     */
//    @Transactional
    public ConversionTaskOutput ConversionTask(ConversionTaskInput input) throws Exception {
        ConversionTaskOutput output = new ConversionTaskOutput();
        UnTasks oldUnTask = new UnTasks();

        if(!isBlank(input.getBusinessId()) && !isBlank(input.getAlreadyHandleUserCode())){
            Example example = new Example(UnTasks.class);
            Example.Criteria criteriaKeyword = example.createCriteria();
            criteriaKeyword.andEqualTo("businessId", input.getBusinessId());
            criteriaKeyword.andEqualTo("receiveUserCode", input.getAlreadyHandleUserCode());
            List<UnTasks> unTasks=unTasksMapper.selectByExample(example);
            if(unTasks.size()>1)
                throw new ErrorJsonResult("10000031", "找到多条待办,请联系管理员");
            if(unTasks.size()==0)
                throw new ErrorJsonResult("10000031", "未找到待办信息");
            oldUnTask=unTasks.get(0);
        }
        if(!isBlank(input.getTaskId())){
            oldUnTask=unTasksMapper.selectByPrimaryKey(input.getTaskId());
        }
        if (oldUnTask == null) {
            throw new ErrorJsonResult("10000031", "未找到待办信息");
        }
        if(isBlank(input.getCreateUserId())){
            input.setCreateUserId(input.getAlreadyHandleUserId());
        }
        if(isBlank(input.getCreateUserCode())){
            input.setCreateUserId(input.getAlreadyHandleUserId());
        }
        if(isBlank(input.getCreateUserCode())){
            input.setCreateUserId(input.getAlreadyHandleUserId());
        }
        //生成已办信息
        AlreadyTasks curAlreadyTasks = new AlreadyTasks();
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        curAlreadyTasks.setId(uuid);
        curAlreadyTasks.setUnTaskId(oldUnTask.getId());
        curAlreadyTasks.setAppCode(oldUnTask.getReceiveAppCode());
        curAlreadyTasks.setHandleTime(new Date());
        curAlreadyTasks.setTitle(!isBlank(input.getAlreadyTitle())?input.getAlreadyTitle():oldUnTask.getTitle());
        curAlreadyTasks.setContent(!isBlank(input.getAlreadyContent())?input.getAlreadyContent():oldUnTask.getContent());
        curAlreadyTasks.setPcUrl(!isBlank(input.getAlreadyPcUrl())?input.getAlreadyPcUrl():oldUnTask.getPcUrl());
        curAlreadyTasks.setMobileUrl(!isBlank(input.getAlreadyMobileUrl())?input.getAlreadyMobileUrl():oldUnTask.getMobileUrl());
        curAlreadyTasks.setBusinessType(!isBlank(input.getAlreadyBusinessType())?input.getAlreadyBusinessType():oldUnTask.getBusinessType());
        curAlreadyTasks.setHandleUserId(input.getAlreadyHandleUserId());
        curAlreadyTasks.setHandleUserCode(input.getAlreadyHandleUserCode());
        curAlreadyTasks.setHandleUserName(input.getAlreadyHandleUserName());
        curAlreadyTasks.setGenre(input.getAlreadyGenre());
        curAlreadyTasks.setCreateTime(new Date());
        curAlreadyTasks.setCreateUserId(input.getCreateUserId());
        curAlreadyTasks.setCreateUserCode(input.getCreateUserCode());
        curAlreadyTasks.setCreateUserName(input.getCreateUserName());
        alreadyTasksMapper.insertSelective(curAlreadyTasks);
        //删除待办信息
        unTasksMapper.deleteByPrimaryKey(oldUnTask);
        //将待办信息放入待办历史中
        UnTaskHistorys curUnTaskHistorys = new UnTaskHistorys();
        ObjectUnit.Copy(oldUnTask, curUnTaskHistorys);
        curUnTaskHistorys.setConversionTime(new Date());
        unTaskHistorysMapper.insertSelective(curUnTaskHistorys);
        output.setAlreadyTask(curAlreadyTasks);
        return output;
    }


}
